package com.atguigu.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.common.Constant;
import org.apache.flink.table.types.logical.SmallIntType;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * @author chenlongStart
 * @create 2021-06-28 17:18
 * @desc
 */
public class DimUtil {

    public static JSONObject readDimFromPhoenix(Connection conn,
                                                String table,
                                                Object id) throws Exception {
        String sql = "select * from " + table + " where id=?";
        List<JSONObject> result = JDBCUtil.queryList(conn, sql, new Object[]{id.toString()}, JSONObject.class);
        if (result!=null && result.size()>0){
            return result.get(0);
        }

        return new JSONObject();
    }

    public static void main(String[] args) throws Exception {
        Connection conn = JDBCUtil.getJdbcConnection(Constant.PHOENIX_DRIVER, Constant.PHOENIX_URL);
        JSONObject object = readDimFromPhoenix(conn, "dim_user_info", 1);
        System.out.println(object);
    }

    public static JSONObject readDim(Connection conn,
                                     Jedis jedis,
                                     String table,
                                     Long id) throws Exception {
        jedis.select(1); // 把数据保存1号库

        // 首先去缓存中读取, 缓存没有在从hbase中读取
        JSONObject dim = readDimFromCache(jedis, table, id);
        if (dim == null){
//            System.out.println("从 Phoenix  读取维度:" + table + "  " + id);
            dim = readDimFromPhoenix(conn, table, id);
            // 把这次读到的dim数据存储到缓存中. 否则缓存中永远没有数据
            saveDimToCache(jedis,table,id,dim);
        }
//        else {
//            System.out.println("从 缓存  读取维度: " + table + "  " + id);
//        }
        return dim;
    }

    private static void saveDimToCache(Jedis jedis,
                                             String table,
                                             Long id,
                                             JSONObject dim) {
        String key = table + ":" + id;
        String jsonStr = dim.toJSONString();
        // 把维度写入到redis中
        jedis.setex(key,Constant.DIM_EXPIRE_SECOND,jsonStr);
    }

    private static JSONObject readDimFromCache(Jedis jedis,
                                               String table,
                                               Long id) {
        String key = table + ":" + id;
        String jsonStr = jedis.get(key);
        JSONObject dim = null;
        if (jsonStr != null) {
            dim= JSON.parseObject(jsonStr);
            // 每读一个维度, 应该重新计算一个24小时的过期时间
            jedis.expire(key,Constant.DIM_EXPIRE_SECOND);
        }
        return dim;
    }
}
